package com.airnews.ticket.download;

import java.io.File;
import java.io.ObjectInputStream;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.airnews.ticket.R;
import com.airnews.ticket.net.DownloadCallback;
import com.airnews.ticket.net.HttpUtils;


/**
 * 下载视图
 * 功能：
 * 1.显示下载信息：如本地版本，服务器版本
 * 2.下载控制：是否下载
 * @author luoxz
 */
public class DownloadView extends Activity{

	private static String tag = "DownloadView";
	private VersionInfo mInfo;
	private ProgressBar progressBar;//进度条
	private TextView progress_text;
	private DownloadTask downloadTask;//下载线程
	private Button btn_confirm, btn_cancel;
	private String apkName;//apk文件名
	private File file;
	private NotificationManager manager = null;
	private RemoteViews view = null;
	private Notification notification = new Notification();
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			view.setProgressBar(R.id.pb, 100, msg.arg1, false);
			if(msg.arg1 == 100){
				view.setTextViewText(R.id.tv, "下载完成");
				manager.cancel(R.drawable.icon);//清除通知
			}else{
				view.setTextViewText(R.id.tv, "下载" + msg.arg1 + "%");
				manager.notify(R.drawable.icon, notification);// 关键部分，如果你不重新更新通知，进度条是不会更新的
			}
		}
	};
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.progress_update);
		mInfo = (VersionInfo) getIntent().getSerializableExtra("versionInfo");
		if(mInfo == null){
			getNewVersionInfo();
		}
		initApkFile();
		setupView();
	}

	
	/**
	 * 从 本地取新版本信息 
	 */
	private void getNewVersionInfo() {
		try {
			ObjectInputStream in = new ObjectInputStream(openFileInput("VersionInfo"));
			mInfo = (VersionInfo)in.readObject();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	private void initApkFile() {
		apkName = getPackageName()+".apk";
		File tempApk = new File(getFilesDir(),apkName);
		if(tempApk.exists()){
			tempApk.delete();
			Log.e(tag, "tempApk is deleted");
		}
	}


	private void setupView(){
		progressBar = (ProgressBar)findViewById(R.id.download_progress);
		btn_confirm = (Button)findViewById(R.id.btn_confirm);
		btn_cancel = (Button)findViewById(R.id.btn_cancel);
		btn_confirm.setOnClickListener(buttonclick);
		btn_cancel.setOnClickListener(buttonclick);
		
		progress_text = (TextView)findViewById(R.id.progress_text);
		TextView updateDesc = (TextView)findViewById(R.id.updateDesc);
		StringBuilder desc = new StringBuilder("当前版本：").append(mInfo.localVersion).append("\n");
		desc.append("服务器版本：").append(mInfo.version).append("\n");
		desc.append(mInfo.desc);
		updateDesc.setText(desc);
		
		
		manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		view = new RemoteViews(getPackageName(), R.layout.progress_notice);
		Intent intent = new Intent(this, DownloadView.class);
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		
		notification.contentView = view;
		notification.contentIntent = pIntent;
		// 通知的图标必须设置(其他属性为可选设置),否则通知无法显示
		notification.icon = R.drawable.icon;
		view.setImageViewResource(R.id.image, R.drawable.icon);// 起一个线程用来更新progress
	}
	
	
	
	
	private View.OnClickListener buttonclick = new OnClickListener(){
		public void onClick(View v) {
			switch(v.getId()){
				case R.id.btn_confirm:{//下载
					downloadTask = new DownloadTask();
					downloadTask.execute(mInfo.path);
					break;
				}
				case R.id.btn_cancel:{//取消下载
					finish();
					if(downloadTask != null){
						downloadTask.isCancelled = true;
						downloadTask.cancel(true);
					}
					break;
				}
			}
		}
	};
	
	
	/**
	 * 下载进程
	 */
	private class DownloadTask extends AsyncTask<String, Integer, Boolean> {

		private boolean isCancelled;//是否已取消
		
		@Override
		protected void onPreExecute() {
			progressBar.setVisibility(View.VISIBLE);
			btn_confirm.setEnabled(false);
			progress_text.setText("开始下载...");
		}

		@Override
		protected Boolean doInBackground(String... params) {
			
			return HttpUtils.downloadFile(DownloadView.this, params[0], file, new DownloadCallback() {
				public boolean onProgressChanged(int progress, int downloadSize, int total) {
					publishProgress(progress, downloadSize, total);
					sendMsg(progress);
					Log.i(tag, "===================="+progress);
					return isCancelled;
				}
			});
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			progressBar.setProgress(values[0]);
			progress_text.setText("已下载"+values[1]/1024+"K/"+values[2]/1024+"K   "+values[0]+"%");
		}

		@Override
		public void onPostExecute(Boolean isSccuess) {//安装apk
			if(isSccuess){
				Intent apkintent = new Intent(Intent.ACTION_VIEW); 
				apkintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			    Uri puri = Uri.fromFile(file);
			    apkintent.setDataAndType(puri, "application/vnd.android.package-archive");  
			    startActivity(apkintent);
			}
			finish();
		}
	}
	
	/**
	 * 发送进度消息
	 * @param progress
	 */
	private void sendMsg(int progress) {
		Message msg = Message.obtain();
		msg.arg1 = progress;
		handler.sendMessage(msg);
	}

}